import UIKit

class SelectButton: UIButton {

  private(set) var isSelectedState: Bool = false {
    didSet {
      updateAppearance()
    }
  }

  weak var manager: SortButtonManager?  // 管理器，弱引用，避免循环引用

  var onSelectedChanged: ((Bool) -> Void)?

  override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
  }

  required init?(coder: NSCoder) {
    super.init(coder: coder)
    setup()
  }

  private func setup() {
    addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
    setTitleColor(.black, for: .normal)
    titleLabel?.font = UIFont.systemFont(ofSize: 14)
    updateAppearance()
  }

  @objc func buttonTapped() {
    manager?.buttonTapped(self)
  }
  private func toggleSelection() {
    isSelectedState.toggle()
    onSelectedChanged?(isSelectedState)
  }

  private func updateAppearance() {
    setImage(nil, for: .normal)
    let color: UIColor = isSelectedState ? .orange : .black
    setTitleColor(color, for: .normal)
  }
}

extension SelectButton: SelectableButton {
  func onTapped() {
    toggleSelection()
  }

  func resetToDefault() {
    isSelectedState = false
  }

}
